package com.neusoft.databus.core.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.databus.common.model.Resource;
import com.neusoft.databus.core.repository.GatewayRepository;
import com.neusoft.databus.core.repository.ResourceRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api("统计控制器")
@RestController
@RequestMapping(value = "/api/w/statistics")
public class StatisticController {
    @Autowired
    private GatewayRepository gatewayRepository;
    @Autowired
    private ResourceRepository resourceRepository;

    @ApiOperation("网关统计")
    @GetMapping("/gateway/count")
    public ResultDTO<Long> gatewayCount() {
        final long count = this.gatewayRepository.count();
        return ResultDTO.success(count);
    }

    @ApiOperation("资源统计")
    @GetMapping("/resource/count")
    @Cacheable("statisticsResourceCount")
    public ResultDTO<Long> resourceCount() {
        final long count = this.resourceRepository.count();
        return ResultDTO.success(count);
    }

    @ApiOperation("点位统计")
    @GetMapping("/metric/count")
    @Cacheable("statisticsMetricCount")
    public ResultDTO<Integer> metricWorkCount() {
        final List<Resource> resources = this.resourceRepository.findAll();

        final int workCount = resources.stream().mapToInt(m -> {

            final int metricCountOfR = m.getMetricGroups().stream().mapToInt(mg -> {
                return mg.getMetrics().size();
            }).sum();

            return metricCountOfR;

        }).sum();

        return ResultDTO.success(workCount);
    }

    @ApiOperation("活跃资源数统计")
    @GetMapping("/resource/activeCount")
    public ResultDTO<Long> activeResourceCount() {
        final long count = this.resourceRepository.activeResourceCount();
        return ResultDTO.success(count);
    }

    @ApiOperation("点位统计")
    @GetMapping("/metric/activeCount")
    public ResultDTO<Integer> activeMetricWorkCount() {
        final List<Resource> resources = this.resourceRepository.findByDisabledAndGateway_disabled(false, false);

        final int workCount = resources.stream().mapToInt(m -> {

            final int metricCountOfR = m.getMetricGroups().stream().mapToInt(mg -> {
                return mg.getMetrics().size();
            }).sum();

            return metricCountOfR;

        }).sum();

        return ResultDTO.success(workCount);
    }

}
